package com.qike.duola.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qike.duola.domain.DuolaDept;
import com.qike.duola.domain.DuolaDeptExample;
import com.qike.duola.dto.DeptAddDto;
import com.qike.duola.dto.DeptDelDto;
import com.qike.duola.dto.DeptEditDto;
import com.qike.duola.dto.DeptListDto;
import com.qike.duola.enums.ErrorEnums;
import com.qike.duola.enums.StatusEnums;
import com.qike.duola.mapper.DuolaDeptMapper;
import com.qike.duola.service.DuolaCustomerService;
import com.qike.duola.service.DuolaDeptService;
import com.qike.duola.utils.TimeTool;
import com.qike.duola.vo.DeptListVo;
import com.qike.duola.vo.DeptPullListVo;
import com.qike.duola.vo.DeptVoList;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Eric.zhou
 * @Date: 2020/8/25 16:56
 */

@Service
public class DuolaDeptServiceImpl implements DuolaDeptService {

    private static final Logger logger = LoggerFactory.getLogger(DuolaDeptServiceImpl.class);
    @Autowired
    private DuolaDeptMapper duolaDeptMapper;


    /**
     * 添加部门
     *
     * @param deptAddDto
     */
    @Override
    @CacheEvict(value="getDeptById")
    public void deptAdd(DeptAddDto deptAddDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"添加部门"+ JSON.toJSON(deptAddDto));
        DuolaDept dept = new DuolaDept();
        dept.setDeptName(deptAddDto.getDeptName());
        dept.setDeptPhone(deptAddDto.getDeptPhone());
        dept.setDeptRemark(deptAddDto.getDeptRemark());
        dept.setStatus(StatusEnums.NO.getEcode());
        dept.setParentId(deptAddDto.getParentId());
        dept.setCreateAt(new Date());
        dept.setCreateId(userId);
        duolaDeptMapper.insertSelective(dept);


    }

    /**
     * 编辑部门
     *
     * @param deptEditDto
     */
    @Override
    @CachePut(value="getDeptById",key = "#deptEditDto.id")
    public void deptEdit(DeptEditDto deptEditDto) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"编辑部门"+ JSON.toJSON(deptEditDto));
        DuolaDept duolaDept = duolaDeptMapper.selectByPrimaryKey(deptEditDto.getId());
        if (duolaDept==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        duolaDept.setUpdateAt(new Date());
        duolaDept.setStatus(StatusEnums.YES.getEcode());
        duolaDept.setUpdateId(userId);
        duolaDept.setDeptRemark(deptEditDto.getDeptRemark());
        duolaDept.setDeptPhone(deptEditDto.getDeptPhone());
        duolaDept.setDeptName(deptEditDto.getDeptName());
        duolaDept.setParentId(deptEditDto.getParentId());
        duolaDeptMapper.updateByPrimaryKeySelective(duolaDept);
    }

    /**
     * 部门列表
     *
     * @param deptListDto
     * @return
     */
    @Override
    public DeptListVo deptList(DeptListDto deptListDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"部门列表"+ JSON.toJSON(deptListDto));
        DeptListVo vo = new DeptListVo();
        List<DeptVoList> list = new ArrayList<>();
        DuolaDeptExample example = new DuolaDeptExample();
        DuolaDeptExample.Criteria criteria = example.createCriteria();
        if (deptListDto.getDeptId()!=null){
            criteria.andIdEqualTo(deptListDto.getDeptId());
        }else {
            criteria.andParentIdEqualTo(StatusEnums.YES.getEcode());
        }
        if (!StringUtils.isEmpty(deptListDto.getPhone())){
            criteria.andDeptPhoneEqualTo(deptListDto.getPhone());
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        example.setOrderByClause("create_at desc");
        Page page = PageHelper.startPage(deptListDto.getStartPage(), deptListDto.getPageSize());
        List<DuolaDept> duolaDepts = duolaDeptMapper.selectByExample(example);
        for (DuolaDept duolaDept : duolaDepts) {
            DeptVoList deptVoList = new DeptVoList();
            deptVoList.setAddTime(TimeTool.dateFormatNoTime(duolaDept.getCreateAt()));
            deptVoList.setId(duolaDept.getId());
            deptVoList.setPhone(duolaDept.getDeptPhone());
            deptVoList.setRemark(duolaDept.getDeptRemark());
            if (!duolaDept.getParentId().equals(StatusEnums.YES.getEcode())){
                deptVoList.setParentName(duolaDept.getDeptRemark());
            }
            deptVoList.setDeptName(duolaDept.getDeptName());
//            deptVoList.setParentName(duolaDept.getParentId());
            deptVoList.setChildren(getDeptChild(duolaDept.getId(),duolaDept.getDeptName()));
            list.add(deptVoList);
        }
        vo.setList(list);
        vo.setTotal(page.getTotal());
        return vo;
    }

    /**
     * 部门下拉列表
     *
     * @param deptName
     * @return
     */
    @Override
    public List<DeptPullListVo> deptPullList(String deptName) {
        List<DeptPullListVo> vos = new ArrayList<>();
        DuolaDeptExample example = new DuolaDeptExample();
        DuolaDeptExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(deptName)){
            criteria.andDeptNameLike(deptName);
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        List<DuolaDept> treeList = duolaDeptMapper.selectByExample(example);
        for (DuolaDept dept : treeList) {
            DeptPullListVo vo = new DeptPullListVo();
            vo.setId(dept.getId());
            vo.setName(dept.getDeptName());
            vos.add(vo);
        }
        return vos;
    }

    /**
     * 删除部门
     *
     * @param deptDelDto
     */
    @Override
    public void deptDel(DeptDelDto deptDelDto) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"删除部门"+ JSON.toJSON(deptDelDto));
        DuolaDept dept = duolaDeptMapper.selectByPrimaryKey(deptDelDto.getId());
        if (dept==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        dept.setStatus(StatusEnums.YES.getEcode());
        duolaDeptMapper.updateByPrimaryKeySelective(dept);
    }

    /**
     * 根据部门id获取部门
     *
     * @param id
     */
    @Override

    public DuolaDept getDeptById(Integer id) throws Exception {
        DuolaDept dept = duolaDeptMapper.selectByPrimaryKey(id);
        return dept;
    }

    /**
     * 获取子级递归
     * @param id
     * @return
     */
    private List<DeptVoList> getDeptChild(Integer id,String name) {
        List<DeptVoList> voList = new ArrayList<>();
        DuolaDeptExample example = new DuolaDeptExample();
        example.createCriteria().andParentIdEqualTo(id).andStatusEqualTo(StatusEnums.NO.getEcode());
        List<DuolaDept> treeList = duolaDeptMapper.selectByExample(example);
        for (DuolaDept duolaDept : treeList) {
            DeptVoList vo = new DeptVoList();
            vo.setId(duolaDept.getId());
            vo.setRemark(duolaDept.getDeptRemark());
            vo.setPhone(duolaDept.getDeptPhone());
            vo.setDeptName(duolaDept.getDeptName());
            vo.setAddTime(TimeTool.dateFormatNoTime(duolaDept.getCreateAt()));
            vo.setParentName(name);
            vo.setChildren(getDeptChild(duolaDept.getId(),duolaDept.getDeptName()));
            voList.add(vo);
        }

        return voList;
    }
}
